// utils/eventExecutor.js
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import axios from 'axios'

/**
 * 通用事件执行工具，支持注入上下文和内置方法
 */
export function executeEventHandler(code = '', context = {}) {
    if (!code) return;
    try {
        const fullContext = {
            ...getBuiltInMethods(context),
            ...context
        };
        const fn = new Function(...Object.keys(fullContext), code);
        fn(...Object.values(fullContext));
    } catch (error) {
        console.error('[事件执行失败]', error);
    }
}

/**
 * 提供给事件代码使用的内置方法集合
 */
function getBuiltInMethods(ctx) {
    const getWidgetById = (list, id) => {
        for (let i = list.length - 1; i >= 0; i--) {
            const item = list[i];
            if (item.id === id) {
                return item;
            } else if (item.children && item.children.length > 0) {
                const widget = getWidgetById(item.children, id);
                if (widget) return widget;
            }
        }
        return null;
    }

    return {
        // 设置组件隐藏状态
        setHidden: (hidden) => {
            if (ctx.widgetConfig) ctx.widgetConfig.attributes.hidden = hidden;
        },

        // 获取当前组件值
        getValue: () => {
            return ctx.formData?.[ctx.widgetConfig.id];
        },

        // 设置当前组件值
        setValue: (value) => {
            if (ctx.widgetConfig && ctx.formData) ctx.formData[ctx.widgetConfig.id] = value;
        },

        // 显示提示信息
        notify: (msg, type = 'info', duration = 2000) => {
            ElMessage({
                message: msg,
                type: type,
                showClose: true,
                duration: duration,
            })
        },

        // 获取任意组件值
        getFieldValue: (fieldId) => {
            return ctx.formData?.[fieldId];
        },

        // 设置任意组件值
        setFieldValue: (fieldId, value) => {
            if (ctx.formData) ctx.formData[fieldId] = value;
        },

        // 控制任意组件隐藏/显示
        setFieldHidden: (fieldId, hidden) => {
            const target = getWidgetById(ctx.widgetList, fieldId);
            if (target) target.attributes.hidden = hidden;
        },

        // 获取当前时间字符串：YYYY-MM-DD hh:mm:ss
        now: () => {
            const pad = (n) => n.toString().padStart(2, '0');
            const date = new Date();
            const YYYY = date.getFullYear();
            const MM = pad(date.getMonth() + 1);
            const DD = pad(date.getDate());
            const hh = pad(date.getHours());
            const mm = pad(date.getMinutes());
            const ss = pad(date.getSeconds());
            return `${YYYY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
        },
        getWidgetById,
        request, //添加配置的请求能力
        axios// 添加未配置的请求能力
    };
}

// 可导出更多内置函数或工具方法，如需外部单独调用
export const eventUtils = {
    getBuiltInMethods
};
